package com.learn.tomcat.http;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class HttpServer {

    public static final String WEB_ROOT = System.getProperty("user.dir") + File.separator + "webroot";
    private static final String SHOTDOWN_COMMAND = "/SHOTDOWN";
    private boolean showdown = false;

    public static void main(String[] args) {
        HttpServer server = new HttpServer();
        server.await();
    }

    private void await() {
        ServerSocket serverSocket = null;
        int port = 8080;
        Socket socket = null;
        InputStream input = null;
        OutputStream output = null;
        try {
            serverSocket = new ServerSocket(port, 1, InetAddress.getByName("127.0.0.1"));
            System.out.println("new serverSocket " + serverSocket.getInetAddress().getHostAddress() + ":" + serverSocket.getLocalPort());
            while (!showdown) {
                System.out.println("serverSocket accept");
                socket = serverSocket.accept();
                input = socket.getInputStream();
                output = socket.getOutputStream();

                Request request = new Request(input);
                request.parse();

                Response response = new Response(output);
                response.setRequest(request);
                if (!request.getUri().equals(SHOTDOWN_COMMAND)) {
                    response.sendStaticResource();
                } else {
                    response.sendSHOTDOWN();
                    showdown = true;
                }
            }
            System.out.println("serverSocket showdown seccess");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (output != null) output.close();
                if (input != null) input.close();
                if (socket != null) socket.close();
                if (serverSocket != null) serverSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
